package com.example.webbasic.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.example.webbasic.filter.MyFilter1;
import com.example.webbasic.filter.MyFilter2;
import com.example.webbasic.filter.MyFilter4;
import com.example.webbasic.servlet.MyServlet1;

/**
 * 应用配置
 * @author ben
 * @date 2021-11-06 15:43:39 CST
 */
@Configuration
public class AppConfig {

	/**
	 * 注册MyServlet1
	 * @author ben
	 * @date 2021-11-06 15:46:34 CST
	 * @return
	 */
	@Bean
	public ServletRegistrationBean<MyServlet1> myServlet1() {
		// 接管所有请求
//		return new ServletRegistrationBean<MyServlet1>(new MyServlet1(), "/*");
		
		// 接管/s/ 开头的请求
		// 都行
		return new ServletRegistrationBean<MyServlet1>(new MyServlet1(), "/s/*");
//		return new ServletRegistrationBean<MyServlet1>(new MyServlet1(), false, "/s/*");

		// 接管/s 开头的请求
		// 失败：没有接管到任何请求
//		return new ServletRegistrationBean<MyServlet1>(new MyServlet1(), "/s*");
		// 失败：没有接管到任何请求
//		return new ServletRegistrationBean<MyServlet1>(new MyServlet1(), "/s**");
		
		// 3参数版本
		// 失败：没有接管到任何请求
//		return new ServletRegistrationBean<MyServlet1>(new MyServlet1(), false, "/s*");
	}
	
	@Bean
	public FilterRegistrationBean<MyFilter1> myFilter1() {
		return new FilterRegistrationBean<MyFilter1>(new MyFilter1(), myServlet1());
	}
	
	// 下面两个 Bean 用来验证 过滤器的顺序设置
	// 默认 4>2
	// 设置Order后，顺序变为 2>4
	
	@Bean
	public FilterRegistrationBean<MyFilter4> registerLoginCheckFilter(MyFilter4 myFilter4) {
		FilterRegistrationBean<MyFilter4> bean = new FilterRegistrationBean<MyFilter4>();
		bean.setFilter(myFilter4);
		bean.addUrlPatterns("/*");
		bean.setName("loginFilter");
		bean.setOrder(100);
		return bean;
	}
	
	@Bean
	public FilterRegistrationBean<MyFilter2> registerLoginCheckFilter2() {
		// 新建对象，避免和 自动建立的Bean冲突
		MyFilter2 myFilter2 = new MyFilter2();
		FilterRegistrationBean<MyFilter2> bean = new FilterRegistrationBean<MyFilter2>();
		bean.setFilter(myFilter2);
		bean.addUrlPatterns("/c/*");
		bean.setName("loginFilter2");
		bean.setOrder(-100);
		return bean;
	}

}
